<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getToken } from '@/utils/cookie'
import {
  getPostDetail,
  checkLikeStatus,
  likePost,
  cancelLike,
  getComments,
  createComment,
  checkFavoriteStatus,
  favoritePost,
  cancelFavoritePost,
  reportPost
} from '@/apis/detail'
import CommentItem from '@/components/CommentItem.vue'

const route = useRoute()
const router = useRouter()
const postId = route.params.postId

// 返回首页
const goToHome = () => {
  router.push('/')
}

// 路由导航守卫
onMounted(() => {
  window.addEventListener('popstate', () => {
    router.push('/')
  })
})

// 帖子数据
const post = ref({
  title: '',
  content: '',
  nickName: '',
  createTime: '',
  visitCount: 0,
  likeCount: 0,
  boards: [],
  isLiked: false,
  isFavorited: false
})

// 举报相关状态
const showReportDialog = ref(false)
const reportContent = ref('')
const reportType = ref(1);
const reportTypes = [
  { label: '垃圾广告', value: 1 },   // 对应数据库 1
  { label: '色情低俗', value: 2 },   // 对应数据库 2
  { label: '暴力内容', value: 3 },   // 对应数据库 3
  { label: '仇恨言论', value: 4 },   // 对应数据库 4
  { label: '其他', value: 5 }        // 对应数据库 5
];


// 评论数据
const comments = ref([])
const loading = ref(true)
const replyContent = ref('')
const showCommentForm = ref(false)
const postData = ref()
const commentsData = ref()
// 格式化时间
const formatTime = (timeStr) => {
  return new Date(timeStr).toLocaleString()
}

// 获取帖子详情（已async）
const fetchPostDetail = async () => {
  try {
    loading.value = true
    postData.value = await getPostDetail(postId)
    commentsData.value = await getComments({
      postId,
    })

    post.value = {
      ...postData.value,
      createTime: formatTime(postData.value.createTime)
    }
    
    // 只有登录用户才检查点赞和收藏状态
    if (getToken()) {
      const likeStatus = await checkLikeStatus(postId)
      post.value.isLiked = likeStatus
      const favoriteStatus = await checkFavoriteStatus(postId)
      post.value.isFavorited = favoriteStatus
    }

    

    comments.value = buildCommentTree(commentsData.value)
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 构建评论树结构（同步方法，不需要async）
const buildCommentTree = (flatComments) => {
  const map = {}
  const roots = []

  flatComments.forEach(comment => {
    map[comment.commentId] = {
      ...comment,
      children: Array.isArray(comment.children) ? comment.children : [],
      showReplyForm: false,
      replyContent: '',
      createTime: formatTime(comment.createTime)
    }
  })

  flatComments.forEach(comment => {
    if (comment.parentId && map[comment.parentId]) {
      map[comment.parentId].children.push(map[comment.commentId])
    } else {
      roots.push(map[comment.commentId])
    }
  })

  return roots
}

// 处理点赞（已async）
const handleLike = async () => {
  if (!getToken()) {
    ElMessage.error('请先登录')
    return
  }

  try {
    if (post.value.isLiked) {
      await cancelLike(postId)
      post.value.likeCount--
    } else {
      await likePost(postId)
      post.value.likeCount++
    }
    post.value.isLiked = !post.value.isLiked
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const handleFavorite = async () => {
  if (!getToken()) {
    ElMessage.error('请先登录')
    return
  }

  try {
    if (post.value.isFavorited) {
      await cancelFavoritePost(postId)
    } else {
      await favoritePost(postId)
    }
    post.value.isFavorited = !post.value.isFavorited
    ElMessage.success(post.value.isFavorited ? '收藏成功' : '已取消收藏')
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 处理评论点赞（同步方法，不需要async）
const handleCommentLike = (payload) => {
  if (!getToken()) {
    ElMessage.error('请先登录')
    return
  }

  const updateCommentLikes = (comments) => {
    return comments.map(comment => {
      if (comment.commentId === payload.commentId) {
        return {
          ...comment,
          isLiked: payload.isLiked,
          likeCount: payload.likeCount
        }
      }

      if (comment.children && comment.children.length > 0) {
        return {
          ...comment,
          children: updateCommentLikes(comment.children)
        }
      }

      return comment
    })
  }

  comments.value = updateCommentLikes(comments.value)
}

// 处理回复（同步方法，不需要async）
const handleReply = (payload) => {
  const updateCommentReplies = (comments) => {
    return comments.map(comment => {
      if (comment.commentId === payload.parentId) {
        return {
          ...comment,
          children: [...(Array.isArray(comment.children) ? comment.children : []), {
            ...payload.comment,
            createTime: formatTime(payload.comment.createTime),
            children: []
          }]
        }
      }

      if (comment.children && comment.children.length > 0) {
        return {
          ...comment,
          children: updateCommentReplies(comment.children)
        }
      }

      return comment
    })
  }

  comments.value = updateCommentReplies(comments.value)
}

// 提交评论（已async）
const submitComment = async () => {
  if (!getToken()) {
    ElMessage.error('请先登录')
    return
  }

  if (!replyContent.value.trim()) {
    ElMessage.error('评论内容不能为空')
    return
  }

  try {
    const newComment = await createComment({
      postId,
      content: replyContent.value,
      token: getToken()
    }, {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    comments.value.unshift({
      ...newComment,
      createTime: formatTime(newComment.createTime),
      children: [],
      showReplyForm: false
    })

    replyContent.value = ''
    showCommentForm.value = false
    ElMessage.success('评论成功')
  } catch (error) {
    ElMessage.error('评论失败')
  }
}

// 处理添加评论按钮点击
const handleAddComment = () => {
  if (!getToken()) {
    ElMessage.error('请先登录')
    return
  }
  showCommentForm.value = true
}

// 处理举报提交
const handleReport = async () => {
  if (!getToken()) {
    ElMessage.error('请先登录')
    return
  }
  
  if (!reportType.value) {
    ElMessage.error('请选择举报类型')
    return
  }
  
  if (!reportContent.value.trim()) {
    ElMessage.error('请输入举报内容')
    return
  }
  
  try {
    // 这里需要调用举报API
    await reportPost({
      postId: post.value.postId,
      postTitle: post.value.title,
      reportTitle: post.value.title,
      reportContent: reportContent.value,
      reportType: reportType.value,
      token: getToken()
    })
    
    ElMessage.success('举报成功')
    showReportDialog.value = false
    reportType.value = ''
    reportContent.value = ''
  } catch (error) {
    ElMessage.error('举报失败')
  }
}

// 初始化加载
onMounted(() => {
  fetchPostDetail()
})
</script>

<template>
  <div class="post-container">
    <el-button 
      type="primary" 
      @click="goToHome"
      style="margin-bottom: 20px"
    >
      返回首页
    </el-button>
    <!-- 加载状态 -->
    <div v-if="loading" class="loading">加载中...</div>
    
    <!-- 帖子内容区域 -->
    <div v-else class="post-content">
      <h1>{{ post.title }}</h1>
      <div class="meta">
        <span>作者: {{ post.nickName }}</span>
        <span>发布于: {{ post.createTime }}</span>
        <span>浏览: {{ post.visitCount }}</span>
      </div>

      <div class="actions">
        <button class="like-btn" :class="{ 'liked': post.isLiked }" @click="handleLike">
          {{ post.isLiked ? '已点赞' : '点赞' }} ({{ post.likeCount }})
        </button>
        <button class="favorite-btn" :class="{ 'favorited': post.isFavorited }" @click="handleFavorite" style="margin-left: 10px; padding: 5px 15px; border: 1px solid #ffc107; color: #ffc107; border-radius: 4px; cursor: pointer; background: none;">
          {{ post.isFavorited ? '已收藏' : '收藏' }}
        </button>
        <button class="report-btn" @click="showReportDialog = true" style="margin-left: 10px; padding: 5px 15px; border: 1px solid #f56c6c; color: #f56c6c; border-radius: 4px; cursor: pointer; background: none;">
          举报
        </button>
      </div>

      <!-- 举报弹窗 -->
      <el-dialog v-model="showReportDialog" title="举报帖子" width="30%">
        <el-form>
          <el-form-item label="举报类型">
            <el-select v-model="reportType" placeholder="请选择举报类型" style="width: 100%">
              <el-option
                v-for="item in reportTypes"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="举报内容">
            <el-input
              v-model="reportContent"
              type="textarea"
              :rows="4"
              placeholder="请详细描述举报原因"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showReportDialog = false">取消</el-button>
            <el-button type="primary" @click="handleReport">
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>

      <div class="content">
        {{ post.content }}
      </div>

      <div class="tags">
        <span v-for="board in post.boards" :key="board.boardName" class="tag">
          {{ board.boardName }}
        </span>
      </div>
    </div>

    <!-- 评论区域 -->
    <div class="comments-section">
      <h2>评论 ({{ comments.length }})</h2>

      <!-- 评论表单 -->
      <div class="comment-form" v-if="showCommentForm">
        <textarea v-model="replyContent" placeholder="写下你的评论..."></textarea>
        <div class="actions">
          <button @click="submitComment">提交</button>
          <button @click="showCommentForm = false">取消</button>
        </div>
      </div>
      <button v-else class="add-comment" @click="handleAddComment">
        添加评论
      </button>

      <!-- 评论列表 -->
      <div class="comment-list" v-if="comments.length > 0">
        <CommentItem 
          v-for="comment in comments" 
          :key="comment.commentId" 
          :comment="comment"
          @reply="handleReply"
          @like="handleCommentLike"
          @refresh="fetchPostDetail"
        />
      </div>
      <div v-else class="empty">
        暂无评论，快来发表你的看法吧~
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 样式保持不变 */
.post-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.loading {
  text-align: center;
  padding: 50px;
  color: #666;
}

.post-content {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.post-content h1 {
  font-size: 24px;
  margin-bottom: 10px;
}

.meta {
  color: #666;
  font-size: 14px;
  margin: 10px 0;
  display: flex;
  gap: 15px;
}

.actions {
  margin: 15px 0;
}

.like-btn {
  padding: 5px 15px;
  border: 1px solid #1890ff;
  color: #1890ff;
  border-radius: 4px;
  cursor: pointer;
  background: none;
}

.like-btn.liked {
  background: #1890ff;
  color: white;
}

.content {
  line-height: 1.8;
  margin: 20px 0;
  white-space: pre-line;
}

.tags {
  margin-top: 15px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.tag {
  background: #f0f2f5;
  padding: 3px 10px;
  border-radius: 4px;
  font-size: 12px;
}

.comments-section {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.comments-section h2 {
  font-size: 20px;
  margin-bottom: 15px;
}

.comment-form {
  margin: 20px 0;
}

.comment-form textarea {
  width: 100%;
  min-height: 100px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: vertical;
}

.comment-form .actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 10px;
}

.comment-form .actions button {
  padding: 5px 15px;
  border-radius: 4px;
  cursor: pointer;
}

.comment-form .actions button:first-child {
  background: #1890ff;
  color: white;
  border: none;
}

.comment-form .actions button:last-child {
  background: none;
  border: 1px solid #ddd;
}

.add-comment {
  background: #1890ff;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  margin: 10px 0;
}

.empty {
  color: #999;
  text-align: center;
  padding: 30px 0;
}
</style>